package com.rr.openApi.article.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rr.frame.exception.ServiceException;
import com.rr.frame.utils.UUIDTool;
import com.rr.openApi.article.dao.ArticleMapper;

@Service
public class ArticleService {

	@Autowired
	private ArticleMapper articleMapper;
	
	public String addArticle(Map<String, Object> paraMap) throws ServiceException,Exception{
		Map<String, Object> article = new HashMap<String, Object>();
		
		Date date = new Date();  
		Timestamp timestamp = new Timestamp(date.getTime());
		
		String aid = UUIDTool.getUUID();
		article.put("aid", aid);
		article.put("title", paraMap.get("title").toString());
		article.put("tag", paraMap.get("tag").toString());
		article.put("content", paraMap.get("content").toString());
		article.put("uid", paraMap.get("uid").toString());
		article.put("summary", paraMap.get("summary").toString());
		article.put("created_time", timestamp);
		
		if(null!=paraMap.get("img1")&&!"".equals(paraMap.get("img1"))){
			article.put("img1", paraMap.get("img1").toString());
 		}
		if(null!=paraMap.get("img2")&&!"".equals(paraMap.get("img2"))){
			article.put("img2", paraMap.get("img2").toString());
 		}
		
		int resultNum = articleMapper.addArticle(article);
		if(resultNum < 1){
			throw new ServiceException("FA_FAILED_ADD_ARTICLE", "发布文章失败");
		}
		
		
		return aid;
	}
	
	public String addLike(Map<String, Object> paraMap) throws ServiceException,Exception{
		
		int resultNum = articleMapper.addLike(paraMap.get("aid").toString());
		if(resultNum < 1){
			throw new ServiceException("FA_FAILED_ADD_LIKE", "文章点赞失败");
		}
		return paraMap.get("aid").toString();
	}
	
	public Map<String, Object> getArticleByid(String aid) throws ServiceException,Exception{
		Map<String, Object> article = articleMapper.selectArticleById(aid);
		if (article == null){
			throw new ServiceException("FA_FAILED_ARTICLE_IS_NOT_EXIST", "该文章不存在");
		}
		return article;
	}
	
	public List<Map<String, Object>> getArticleList(Map<String, Object> paraMap) throws ServiceException,Exception{
		
		List<Map<String, Object>> articleList = articleMapper.getArticleList(paraMap);
		return articleList;
	}
	
	public List<Map<String, Object>> getArticleListByKeyWord(Map<String, Object> paraMap) throws ServiceException,Exception{
		
		List<Map<String, Object>> articleList = articleMapper.getArticleListByKeyWord(paraMap);
		return articleList;
	}
}
